package drawapp.cw.com.recyclerviewdemo;

import android.content.Context;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.widget.FrameLayout;
import android.widget.ListAdapter;

/**
 * Created by Ade-rui on 2016/12/19.
 */
public class RefreshLoadingRecyclerView extends FrameLayout implements SwipeRefreshLayout.OnRefreshListener{

    /**
     * 空闲状态
     */
    public static final int STATE_IDLE = 1002;

    /**
     * 加载更多中
     */
    public static final int STATE_LOAD_MORE = 1003;

    /**
     * 刷新中
     */
    public static final int STATE_REFRESH = 1004;

    /**
     * 刷新器
     */
    private SwipeRefreshLayout swipeRefreshLayout;
    /**
     * recyclerview
     */
    private RecyclerView recyclerView;

    /**
     * 刷新与加载的回调监听
     */
    private OnRefreshLoadingListener listener;

    /**
     * 布局管理器
     */
    private ILayoutManager layoutManager;
    /**
     * 适配器
     */
    private BaseRecyclerAdapter adapter;

    /**
     * 当前状态
     * 默认为空闲
     */
    private int mCurrentState = STATE_IDLE;

    /**
     * 是否开启加载更多功能
     */
    private boolean isEnableLoadMore;

    public RefreshLoadingRecyclerView(Context context) {
        super(context);
        init();
    }

    public RefreshLoadingRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        LayoutInflater.from(getContext()).inflate(R.layout.layout_recycler_view,this,true);
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        swipeRefreshLayout.setOnRefreshListener(this);
        //设置recyclerView默认的LayoutManager -- > 相当于普通listview样式
        this.layoutManager = new MyLinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager.getLayoutManager());
        recyclerView.addOnScrollListener(onScrollListener);
    }

    /**
     * 滚动监听
     */
    private RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            /**
             * mCurrentState == STATE_IDLE  因为如果是加载中的话，继续有下拉的动作，还会回调加载
             * ，所以必须是空闲状态下才能回调加载。进入加载回调就立刻将状态修改为加载状态，避免再次回聊。
             * isEnableLoadMore ： 用来手动设置是否开启加载更多的功能
             * loadingSecurity() ：判断是否可以加载更多,如何实现由具体的布局管理器而定
             * dy>0 : 为了返回有时候数据不满一屏，都没有滚动，便发生了加载的情况
             */
            if(mCurrentState == STATE_IDLE&&isEnableLoadMore && loadingSecurity() && dy > 0){
                loadMore();
            }
        }
    };

    /**
     * 设置是否开启加载更多的功能
     * @param isEnableLoadMore
     */
    public void isEnableLoadMore(boolean isEnableLoadMore){
        this.isEnableLoadMore = isEnableLoadMore;
    }

    /**
     * 加载更多
     */
    private void loadMore() {
        if(listener == null){
            return;
        }
        //修改状态
        mCurrentState = STATE_LOAD_MORE;
        //禁止swipeRefreshLayout功能
        swipeRefreshLayout.setEnabled(false);
        //通知adapter显示加载更多的布局
        adapter.loadMoreChangeState(true);
        listener.onLoading();
    }

    /**
     * 完成加载或者刷新
     * 由用户调用
     */
    public void complete(){
        if(mCurrentState == STATE_LOAD_MORE){
            //通知adapter隐藏加载更多布局
            adapter.loadMoreChangeState(false);
            //回复SwipeRefreshLayout功能
            swipeRefreshLayout.setEnabled(true);
        }else if(mCurrentState == STATE_REFRESH){
            //让刷新动画消失
            swipeRefreshLayout.setRefreshing(false);
        }
        mCurrentState = STATE_IDLE;
    }

    /**
     * 是否可以加载
     * 根据具体的LayoutManager实现来判断
     * @return
     */
    private boolean loadingSecurity() {
        return layoutManager.loadMore();
    }

    /**
     * 设置适配器
     * @param adapter
     */
    public void setAdapter(BaseRecyclerAdapter adapter){
        this.adapter = adapter;
        recyclerView.setAdapter(adapter);
    }

    /**
     * 设置布局管理器
     * @param layoutManager
     */
    public void setLayoutManager(ILayoutManager layoutManager){
        this.layoutManager = layoutManager;
        recyclerView.setLayoutManager(layoutManager.getLayoutManager());
    }

    /**
     * 设置刷新加载监听
     * @param listener
     */
    public void setOnRefreshLoadingListener(OnRefreshLoadingListener listener){
        this.listener = listener;
    }

    /**
     * 刷新
     */
    public void setRefresh(){
        /**
         *  使用post加入消息队列调用---》 可以防止第一次进入页面的时候，
         *  虽然执行swipeRefreshLayout.setRefreshing(true)，但并不会显示刷新动画的bug
         */
        post(new Runnable() {
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(true);
                onRefresh();
            }
        });
    }

    /**
     * RereshLayout监听到下拉手势的回调，然后我们在这个回调里面修改自身控件的状态
     * 并且回调总结的listener给用户
     */
    @Override
    public void onRefresh() {
        if(listener!=null){
            mCurrentState = STATE_REFRESH;
            Log.i("mydata","onRefresh");
            listener.onRefresh();
        }
    }

    /**
     * 监听回调
     */
    public interface OnRefreshLoadingListener{
        void onRefresh();
        void onLoading();
    }

}
